
$(function () {
	var AllFormData = new Object;//全部表单数据

	function getUrlParam(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
		var r = window.location.search.substr(1).match(reg);  //匹配目标参数
		if (r != null) return unescape(r[2]); return null; //返回参数值
	}
	//获取详情
	var infoId = parent.window.dataResourcesId;
	if(infoId){
		$(".dataResourceId").val(infoId);
		let loading = layer.load(1);
		$.ajax({
       timeout:30000,
			url: window.Http + "/datasourceBase/"+infoId,
			type: 'GET',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			success: function (res) {
				layer.close(loading);
				if (res.code == 200) {
					AllFormData = res.data;
					if(operateType == 1){
						setInfoData1();
					}
				}else{
					layer.msg(res.msg);
				}
			}
		})
	}

	//选择操作类型
	var operateType = 1;//默认操作类型手动
	layui.form.on('radio(operateType)', function(data){
		$(".layui-form-cont .cont-item").addClass("disabledNone");
		if(data.value == 1){//导入资源文件
			$(".halfArtificia").removeClass("disabledNone");
			$(".halfArtificiaChild").removeClass("disabledNone");
			$(".fullArtificiaChild").addClass("disabledNone");
			$(".resourceFileBox").removeClass("disabledNone");
			//setInfoData2();
			operateType = 2;
			queryDataStatus();
		}else if(data.value == 2){//自动获取资源
			operateType = 3;
			$(".halfArtificia").removeClass("disabledNone");
			$(".halfArtificiaChild").addClass("disabledNone");
			$(".fullArtificiaChild").removeClass("disabledNone");
			$(".resourceFileBox").addClass("disabledNone");
		}else{//人工录入
			operateType = 1;
			$(".allArtificial").removeClass("disabledNone");
			setInfoData1();
		}
	});



	/***********人工录入程序处理***************/

	var SCont_Num = 0,SQL_Num = 0;//动态表格
	var SCont_paramList = [],SQL_paramList = [];
	var selectSQltableId; //选择结构表序号（新增可能没ID）
	var allUsersData = [];

	(function(){
		$.ajax({
       timeout:30000,
			url: window.Http + "/system/user/list/select",
			type: 'GET',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			success: function (res) {
				if (res.code == 200) {
					if (res.rows && res.rows.length > 0) {
						allUsersData = res.rows;
					}
				}
			}
		})
	}())
	// 获取详情后处理数据（人工录入）
	var selectTypeIdList = [];
	var all_pageNum = 1,all_pageSize = 5,all_total=0;//人工录入分页
	function setInfoData1(data){
		// if(data.datasourceStructList&&data.datasourceStructList.length>0){
		// 	SQL_paramList = data.datasourceStructList;
		// 	SQL_Num = data.datasourceStructList.length;
		// 	loopTableRender_SQL();
		// 	renderSQL_select();
		// }
		// selectTypeIdList = data.typeIdList||[];
		$.ajax({
       timeout:30000,
			url: window.Http + "/data/struct/list",
			type: 'GET',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			data:{sourceId:infoId,pageNum:all_pageNum,pageSize:all_pageSize},
			success: function (res) {
				if (res.code == 200) {
					all_total = res.total;
					if(res.rows&&res.rows.length>0){
						SQL_paramList = res.rows;
						loopTableRender_SQL();
						renderSQL_select();
						if(all_pageNum == 1){
							layui.laypage.render({
								elem: 'databaseSQLPage', //注意，这里的 test1 是 ID，不用加 # 号
								count: all_total, //数据总数，从服务端得到
								limit: all_pageSize,
								layout: ['count', 'prev', 'page', 'next', 'limit'],
								jump: function (obj, first) {
									if(!first){
									  all_pageNum = obj.curr;
									  all_pageSize = obj.limit;
									  setInfoData1();
									}
								}
							});
						}
					}else{
						SQL_paramList = [];
						loopTableRender_SQL();
						layui.laypage.render({
							elem: 'databaseSQLPage', //注意，这里的 test1 是 ID，不用加 # 号
							count: 0, //数据总数，从服务端得到
							limit: all_pageSize,
							layout: ['count', 'prev', 'page', 'next', 'limit']
						});
					}
				}else{
					layer.msg(res.msg);
				}
			}
		})
	}

	//添加选择用户列表
	function getSelectUsers(e){
		let obj = e?e:$(".selectUsers");
		$.ajax({
       timeout:30000,
			url: window.Http + "/system/user/list/select",
			type: 'GET',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			data:{userName:""},
			success: function (res) {
				if (res.code == 200) {
					obj.find("select").empty();
					if (res.rows && res.rows.length > 0) {
						let html = `<option value="">所有人</option>`;
						res.rows.forEach(function (val, index) {
							html += `<option value="${val.userId}">${val.nickName}</option>`
						})
						obj.find("select").append(html);
					}else{
						let html = `<option value="">所有人</option>`
						obj.find("select").append(html);
					}
					layui.form.render();
				}
			}
		})
	}

	//渲染资源内容当前选中内容结构
	function renderSQL_select(){
		$(".SesourceContentId").empty();
		let html = `<option  value="">请选择</option>`;
		SQL_paramList.forEach(function (val, index) {
			if(selectSQltableId == val.id){
				html += `<option value="${val.id}" selected>${val.classAlias}</option>`;
				SCont_paramList = val.datasourceContentList||[];
				SCont_Num = SCont_paramList.length;
			}else{
				html += `<option value="${val.id}">${val.classAlias}</option>`;
			}

		})
		$(".SesourceContentId").append(html);
		layui.form.render();
		loopTableRender_SCont();
	}



	function loopTableRender_SQL(){//结构信息
		$("#databaseSQL tbody").empty();
		let html = '';
		let data = SQL_paramList;
		data.forEach(function(val,index){
			let deleteHtml = `<span class="deleteTrItem"><img class="" src="assets/img/demo/delete.png" title="删除" alt="删除" style="width:30px;cursor: pointer;"></span>
							<span class="saveTrItem"><img class="" src="assets/img/demo/save.png" title="保存" alt="保存" style="width:30px;cursor: pointer;"></span>
							`
			html+= `<tr dataIndex = ${index+1} dataId =${val.id}>
						<td>${index+1}</td>
						<td><input type="text" class="DatabaseSQL_classAlias" placeholder="表别名(不可重复)" value=${val.classAlias}></td>
						<td><input type="text" class="DatabaseSQL_representation" placeholder="表名(不可重复)"  value=${val.representation}></td>
						<td><input type="text" class="DatabaseSQL_keyword" placeholder="表关键字"  value=${val.keyword||"无"}></td>
						<td><input type="text" class="DatabaseSQL_remark" placeholder="说明" value=${val.remark||""}></td>
						<td class="controlDel cDel" style="border:none;">`+deleteHtml+`</td>
					</tr>`;
		})
		$("#databaseSQL tbody").append(html);
		layui.form.render();
	}

	function loopTableRender_SCont(){//资源
		$("#sesourceContent tbody").empty();
		let html = '';
		let data = SCont_paramList;
		data.forEach(function(val,index){
			let deleteHtml = `<span class="deleteTrItem"><img class="" src="assets/img/demo/delete.png" title="删除" alt="删除" style="width:30px;cursor: pointer;"></span>
							<span class="saveTrItem"><img class="" src="assets/img/demo/save.png" title="保存" alt="保存" style="width:30px;cursor: pointer;"></span>`
			//dataType
			let htmlDataType = `<select class="SesourceContent_dataType">
										<option value="">请选择</option>
										<option value="0">整数</option>
										<option value="1">长整数</option>
										<option value="2">字节</option>
										<option value="3">浮点数</option>
										<option value="4">时间</option>
										<option value="5">字符串</option>
									</select>`
			if(val.dataType == '0'){
				htmlDataType = `<select class="SesourceContent_dataType">
										<option value="">请选择</option>
										<option value="0" selected>整数</option>
										<option value="1">长整数</option>
										<option value="2">字节</option>
										<option value="3">浮点数</option>
										<option value="4">时间</option>
										<option value="5">字符串</option>
									</select>`
			}else if(val.dataType == '1'){
				htmlDataType = `<select class="SesourceContent_dataType">
										<option value="">请选择</option>
										<option value="0" >整数</option>
										<option value="1" selected>长整数</option>
										<option value="2">字节</option>
										<option value="3">浮点数</option>
										<option value="4">时间</option>
										<option value="5">字符串</option>
									</select>`
			}else if(val.dataType == '2'){
				htmlDataType = `<select class="SesourceContent_dataType">
										<option value="">请选择</option>
										<option value="0" >整数</option>
										<option value="1" >长整数</option>
										<option value="2" selected>字节</option>
										<option value="3">浮点数</option>
										<option value="4">时间</option>
										<option value="5">字符串</option>
									</select>`
			}else if(val.dataType == '3'){
				htmlDataType = `<select class="SesourceContent_dataType">
										<option value="">请选择</option>
										<option value="0" >整数</option>
										<option value="1" >长整数</option>
										<option value="2" >字节</option>
										<option value="3" selected>浮点数</option>
										<option value="4">时间</option>
										<option value="5">字符串</option>
									</select>`
			}else if(val.dataType == '4'){
				htmlDataType = `<select class="SesourceContent_dataType">
										<option value="">请选择</option>
										<option value="0" >整数</option>
										<option value="1" >长整数</option>
										<option value="2" >字节</option>
										<option value="3" >浮点数</option>
										<option value="4" selected>时间</option>
										<option value="5">字符串</option>
									</select>`
			}else if(val.dataType == '5'){
				htmlDataType = `<select class="SesourceContent_dataType">
										<option value="">请选择</option>
										<option value="0" >整数</option>
										<option value="1" >长整数</option>
										<option value="2" >字节</option>
										<option value="3" >浮点数</option>
										<option value="4" >时间</option>
										<option value="5" selected>字符串</option>
									</select>`
			}


			html+= `<tr dataIndex = ${index+1} dataId =${val.id}>
						<td>${index+1}</td>
						<td><input type="text" class="SesourceContent_name" style="width:100px" value=${val.name||""} /></td>
						<td><input type="text" class="SesourceContent_columnName" style="width:100px" value=${val.columnName||""} /></td>
						<td><input type="text" class="SesourceContent_remark" style="width:100px" value=${val.remark||""} /></td>
						<td class="controlDel cDel" style="border:none;">${deleteHtml}</td>
					</tr>`;
		})

		$("#sesourceContent tbody").append(html);
		layui.form.render();
	}
	//处理数据paramList
	function MakeParamList(DataType,I,Key,Value){
		if(DataType == "SQL"){
			SQL_paramList.forEach(function(obj,index){
				if(I==(index+1)){
					obj[Key] = Value;
				}
			})

		}else if(DataType == "SCont"){
			SCont_paramList.forEach(function(obj,index){
				if(I==(index+1)){
					obj[Key] = Value;
				}
			})
			SQL_paramList.forEach(function(val,i){
				if(selectSQltableId == val.id){
					val.datasourceContentList = SCont_paramList
				}
			})
			// SQL_paramList[selectSQltable].datasourceContentList = SCont_paramList;
		}

	}
	//资源内容(新增)
	// function SesourceContentDOM() {
	// 	SCont_Num++;
	// 	let deleteHtml = `<span class="deleteTrItem"><img class="" src="assets/img/demo/delete.png" title="删除" alt="删除" style="width:30px;cursor: pointer;"></span>
	// 						<span class="saveTrItem"><img class="" src="assets/img/demo/save.png" title="保存" alt="保存" style="width:30px;cursor: pointer;"></span>`
	// 	let html = `<tr dataIndex=`+SCont_Num+`>
	// 			<td>`+SCont_Num+`</td>
	// 			<td><input type="text" value="" class="SesourceContent_name" style="width:100px"></td>
	// 			<td><input type="text" value="" class="SesourceContent_columnName" style="width:100px"></td>
	// 			<td class="select">
	// 				<select class="SesourceContent_dataType">
	// 					<option value="">请选择</option>
	// 					<option value="0">整数</option>
	// 					<option value="1">长整数</option>
	// 					<option value="2">字节</option>
	// 					<option value="3">浮点数</option>
	// 					<option value="4">时间</option>
	// 					<option value="5">字符串</option>
	// 				</select></td>
	// 			<td><input type="text" value="" class="SesourceContent_remark" value="" style="width:100px"></td>
	// 			<td class="controlDel cDel" style="border:none;">`+deleteHtml+`</td>
	// 		</tr>`
	// 	$("#sesourceContent tbody").append(html);
	// 	layui.form.render();
	// }
	//结构信息(新增)
	// function DatabaseSQLDOM() {
	// 	SQL_Num++;
	// 	let deleteHtml = `<span class="deleteTrItem"><img class="" src="assets/img/demo/delete.png" title="删除" alt="删除" style="width:30px;cursor: pointer;"></span>
	// 						<span class="saveTrItem"><img class="" src="assets/img/demo/save.png" title="保存" alt="保存" style="width:30px;cursor: pointer;"></span>`
	// 	let html = `<tr dataIndex=`+SQL_Num+`>
	// 			<td>`+SQL_Num+`</td>
	// 			<td><input type="text" class="DatabaseSQL_classAlias" placeholder="表别名(不可重复)"></td>
	// 			<td><input type="text" class="DatabaseSQL_representation" placeholder="表名(不可重复)"></td>
	// 			<td><input type="text" class="DatabaseSQL_keyword" placeholder="表关键字"></td>
	// 			<td><input type="text" class="DatabaseSQL_remark" placeholder="说明"></td>
	// 			<td class="controlDel cDel" style="border:none;">`+deleteHtml+`</td>
	// 		</tr>`
	// 	$("#databaseSQL tbody").append(html);
	// 	layui.form.render();
	// }

	// 结构信息删除行
	$("#databaseSQL").on("click",'.deleteTrItem',function (){
		let index = $(this).parents("tr").attr("dataIndex");
		let dataId = $(this).parents("tr").attr("dataId");
		if (confirm("是否删除当前第几["+index+']行资源结构')){
			// $(this).parents("tr").remove();
			// SQL_Num--;
			// SQL_paramList.splice((index-1),1);
			// loopTableRender_SQL();
			$.ajax({
       timeout:30000,
				url: window.Http + "/data/struct/del",
				type: 'DELETE',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				data: {datasourceStructId:dataId},
				success: function (res) {
					if(res.code == 200){
						layer.msg("删除成功", {icon: 1});
						setInfoData1();
					}else{
						layer.msg(res.msg, {icon: 2});
					}
				}
			})
		}
	})
	// 结构信息添加行
	$("#databaseSQL").on("click",'.addTrItem',function (){
		let obj = {
			classAlias: "未填写",
			representation: "未填写",
			remark: "",
			keyword:"",
			sourceId:infoId,
			datasourceContentList:[]
		}
		$.ajax({
       timeout:30000,
			url: window.Http + "/data/struct/save",
			type: 'POST',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			data: JSON.stringify(obj),
			contentType:"application/json",
			success: function (res) {
				if(res.code == 200){
					layer.msg("新增成功", {icon: 1});
					all_pageNum = 1;
					setInfoData1();
				}else{
					layer.msg(res.msg, {icon: 2});
				}
			}
		})
	})
	//保存资源结构
	$("#databaseSQL").on("click",'.saveTrItem',function (){
		let dataId = $(this).parents("tr").attr("dataId");
		SQL_paramList.forEach((value,index)=>{
			if(value.id == dataId){
				all_saveFunction(value,1)
			}
		})
	})

	// 资源内容删除行
	$("#sesourceContent").on("click",'.deleteTrItem',function (){
		let index = $(this).parents("tr").attr("dataIndex");
		let dataId = $(this).parents("tr").attr("dataId");
		if (confirm("是否删除当前第几["+index+']行资源内容')){
			// $(this).parents("tr").remove();
			// PSet_Num--;
			// SCont_paramList.splice((index-1),1);
			// loopTableRender_SCont();
			SQL_paramList.forEach((value,index)=>{
				if(value.id == selectSQltableId){
					value.datasourceContentList.forEach((val,i)=>{
						if(val.id == dataId){
							value.datasourceContentList.splice(i,1);
							all_saveFunction(value,3);
							return;
						}
					})
				}

			})
		}
	})
	// 资源内容添加行
	$("#sesourceContent").on("click",'.addTrItem',function (){
		if(selectSQltableId){
			let data = {
				columnName: "未填写",
				dataType: "5",
				name: "未填写",
				remark: "暂无",
				tableName: ""
			}
			let obj;
			SQL_paramList.forEach(function(val,i){
				if(selectSQltableId == val.id){
					obj = val;
				}
			})
			obj.datasourceContentList.push(data);
			$.ajax({
       timeout:30000,
				url: window.Http + "/data/struct/save",
				type: 'POST',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				data: JSON.stringify(obj),
				contentType:"application/json",
				success: function (res) {
					if(res.code == 200){
						layer.msg("新增成功", {icon: 1});
						all_pageNum = 1;
						setInfoData1();
					}else{
						layer.msg(res.msg, {icon: 2});
					}
				}
			})
		}else{
			layer.msg("请选择需要操作的资源结构");
		}

	})
	//保存资源内容
	$("#sesourceContent").on("click",'.saveTrItem',function (){
		let dataId = $(this).parents("tr").attr("dataId");
		SQL_paramList.forEach((value,index)=>{
			if(value.id == selectSQltableId){
				value.datasourceContentList.forEach((val,i)=>{
					if(val.id == dataId){
						all_saveFunction(value,2);
						return;
					}
				})
			}
		})
	})

	//表格中表单动态绑定事件(资源内容)
	$('#sesourceContent').on('blur', '.SesourceContent_name', function () {
		let val = $(this).val();
		let index = $(this).parents("tr").attr("dataIndex");
		MakeParamList("SCont",index,"name",val);
	})
	$('#sesourceContent').on('blur', '.SesourceContent_columnName', function () {
		let val = $(this).val();
		let index = $(this).parents("tr").attr("dataIndex");
		MakeParamList("SCont",index,"columnName",val);
	})
	$('#sesourceContent').on('blur', '.SesourceContent_remark', function () {
		let val = $(this).val();
		let index = $(this).parents("tr").attr("dataIndex");
		MakeParamList("SCont",index,"remark",val);
	})


	//表格中表单动态绑定事件(结构信息)
	$('#databaseSQL').on('blur', '.DatabaseSQL_classAlias', function () {
		let val = $(this).val();
		let index = $(this).parents("tr").attr("dataIndex");
		MakeParamList("SQL",index,"classAlias",val);
	})
	$('#databaseSQL').on('blur', '.DatabaseSQL_representation', function () {
		let val = $(this).val();
		let index = $(this).parents("tr").attr("dataIndex");
		MakeParamList("SQL",index,"representation",val);
	})
	$('#databaseSQL').on('blur', '.DatabaseSQL_keyword', function () {
		let val = $(this).val();
		let reg=/\\|\/|\;|\;|\，|\,|\、|\、|\^|\`|\|/g;
		val = val.replace(reg,",");
		let index = $(this).parents("tr").attr("dataIndex");
		MakeParamList("SQL",index,"keyword",val);
	})
	$('#databaseSQL').on('blur', '.DatabaseSQL_remark', function () {
		let val = $(this).val();
		let index = $(this).parents("tr").attr("dataIndex");
		MakeParamList("SQL",index,"remark",val);
	})
	layui.form.on('select()', function(data){
	  let val = data.value;
	  let index = data.othis.parents("tr").attr("dataIndex");
	  if(data.elem.className.indexOf("SesourceContent_dataType") != -1){//内容设置
		  MakeParamList("SCont",index,"dataType",val);
	  }else if(data.elem.className.indexOf("SesourceContentId") != -1){
		  //选择数表
		  SQL_paramList.forEach(function (val, index) {
			   if(data.value == val.id){
				   selectSQltableId = data.value;
				   SCont_paramList = val.datasourceContentList||[];
				   SCont_Num = SCont_paramList.length;
			       loopTableRender_SCont();
			   }
		  })
	  }
	});
	//保存表或字段
	function all_saveFunction(obj,type){
		$.ajax({
       timeout:30000,
			url: window.Http + "/data/struct/save",
			type: 'POST',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			data: JSON.stringify(obj),
			contentType:"application/json",
			success: function (res) {
				if(res.code == 200){
					if(type == 1){
						layer.msg("资源结构保存成功", {icon: 1});
					}else if(type == 2){
						layer.msg("资源内容保存成功", {icon: 1});
					}else if(type == 3){
						layer.msg("资源内容删除成功", {icon: 1});
					}
					all_pageNum = 1;
					setInfoData1();
				}else{
					layer.msg(res.msg, {icon: 2});
				}
			}
		})
	}

	/***********人工录入程序处理结束***************/




	/***********导入资源文件程序处理***************/
	//显示数据、操作数据
	var operateData = [],currentData = {};
	var loadIndex; //loading
	var half_pageNum = 1,half_pageSize = 10,half_total=0;//分页
	// 获取详情后处理数据（导入资源文件）
	function setInfoData2(){
		$.ajax({
       timeout:30000,
			url: window.Http + "/data/struct/list",
			type: 'GET',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			data:{sourceId:infoId,pageNum:half_pageNum,pageSize:half_pageSize},
			success: function (res) {
				if (res.code == 200) {
					half_total = res.total;
					if(res.rows&&res.rows.length>0){
						operateData = res.rows;
						dealShowDataFun();
						if(half_pageNum == 1){
							layui.laypage.render({
								elem: 'treeStructurePage', //注意，这里的 test1 是 ID，不用加 # 号
								count: half_total, //数据总数，从服务端得到
								limit: half_pageSize,
								layout: ['count', 'prev', 'page', 'next', 'limit'],
								jump: function (obj, first) {
									if(!first){
									  half_pageNum = obj.curr;
									  half_pageSize = obj.limit;
									  setInfoData2();
									}
								}
							});
						}
					}else{
						operateData = [];
						dealShowDataFun();
					}
				}else{
					layer.msg(res.msg);
				}
			}
		})
	}
	var analysis_timer;
	var resourceFile,ruleFile;
	//选择资源文件
	$('#resourceFile').change(function (event) {
	    for (let i = 0; i < event.target.files.length; i++) {
	    	// 获取input上传附件
	    	let file = event.target.files[i];
			if(file&&file.size > (50*1024*1024)){
				layer.msg("上传文件过大，资源结构文件需小于50M");
			}else{
				resourceFile = file;
				//uploadFile(file,"idCardFrontFile");
			}

	    }
	});
	//选择规则文件
	$('#ruleFile').change(function (event) {
	    for (let i = 0; i < event.target.files.length; i++) {
	    	// 获取input上传附件
	    	let file = event.target.files[i];
			if(file&&file.size > (10*1024*1024)){
				layer.msg("上传文件过大，资源结构文件需小于10M");
			}else{
				ruleFile = file;
			}

	    }
	});
	$("body").on("click",'#uploadFile',function (e){
		e.preventDefault();
		if(resourceFile){
			uploadFile(resourceFile,ruleFile);
		}else{
			layer.msg("请选择资源文件");
		}
		firstShow = true;
	})
	//上传附件
	function uploadFile(resourceFile,ruleFile,name) {
		loadIndex = layer.load(1); //换了种风格
	    var form = new FormData();
		form.append('file', resourceFile);
		form.append('rule', ruleFile);
		form.append('sourceId', infoId);
	    $.ajax({
       timeout:30000,
			url:window.Http+"/datasourceBase/analysis",
			type:'POST',
			headers: {
			　　'Authorization':"Bearer "+sessionStorage.getItem('Token')
			},
			data:form,
			mimeType:"multipart/form-data",
			contentType:false,
			processData:false,
			dataType:"json",
			success:function (res){
				layer.close(loadIndex);
				if(res.code == 200){
					queryDataStatus();//立即执行一次
					if(!analysis_timer){
						analysis_timer = setInterval(function(){
						   queryDataStatus();
						},5000)
					}
				}else{
					layer.msg(res.msg);
				}
			},
			error:function(err){
				layer.close(loadIndex);
				layer.msg(err.msg);
			}
	    })
	};
	var firstShow = false;
	//查询上传文件解析数据状态
	function queryDataStatus(){
		if(!analysis_timer){
			analysis_timer = setInterval(function(){
			   queryDataStatus();
			},5000)
		}
		$.ajax({
       timeout:30000,
			url:window.Http+"/datasourceBase/taskInfo",
			type:'GET',
			headers: {
			　　'Authorization':"Bearer "+sessionStorage.getItem('Token')
			},
			data:{sourceId:infoId},
			success:function (res){
				if(res.code == 200){
					if(!res.data){
						$("#fileAnalysis").addClass("disabledNone");
						clearTimeout(analysis_timer);
						analysis_timer = null;
					}else if(res.data.execStatus == 2){
						layer.close(loadIndex);
						setInfoData2();
						if(firstShow){
							$("#fileAnalysis").removeClass("disabledNone");
							$("#fileAnalysis").find("p").text("解析成功");
						}else{
							$("#fileAnalysis").addClass("disabledNone");
						}
						clearTimeout(analysis_timer);
						analysis_timer = null;
					}else if(res.data.execStatus == 3){
						layer.close(loadIndex);
						$("#fileAnalysis").removeClass("disabledNone");
						$("#fileAnalysis").find("p").text(res.data.execResult);
						clearTimeout(analysis_timer);
						analysis_timer = null;
					}else if(res.data.execStatus == 0 || res.data.execStatus == 1){
						layer.close(loadIndex);
						$("#fileAnalysis").removeClass("disabledNone");
						$("#fileAnalysis").find("p").text(res.data.execResult);
					}else if(res.data.execStatus == -1){
						layer.close(loadIndex);
						$("#fileAnalysis").removeClass("disabledNone");
						$("#fileAnalysis").find("p").text(res.data.execResult);
						clearTimeout(analysis_timer);
						analysis_timer = null;
					}
				}else{
					layer.close(loadIndex);
					layer.msg(res.msg);
					clearTimeout(analysis_timer);
					analysis_timer = null;
				}
			},
			error:function(err){
				layer.close(loadIndex);
				layer.msg(err.msg);
				clearTimeout(analysis_timer);
				analysis_timer = null;
			}
		})
	}

	//渲染资源节点
	var resourcesTree;
	function renderResources(){
		layer.close(loadIndex);
		layui.use(['tree', 'layer', 'util'], function(){
			resourcesTree = layui.tree;
			var layer = layui.layer,util = layui.util;
			resourcesTree.render({
				elem: '#treeStructure',
				data: operateData,
				onlyIconControl: true,  //是否仅允许节点左侧图标控制展开收缩
				edit: ['add','del'], //操作节点的图标
				click: function(obj){
				    clickTreeData(obj);
				},
				operate: function(obj){
					operateTreeData(obj);
				},
				oncheck: function(obj){
					checkedTreeData(obj);
				}
			});
		})
	}

	//点击资源树
	function clickTreeData(obj){
		operateData.forEach((value,index)=>{
			if(value == obj.data){
				value.edit = true;
				value.spread = true;
			}else{
				value.edit = false;
				value.spread = false;
			}
			if(value.datasourceContentList && value.datasourceContentList.length>0){
				let childData = value.datasourceContentList;
				childData.forEach((val,i)=>{
					if(val == obj.data){
						val.edit = true;
						value.spread = true;
					}else{
					  	val.edit = false;
					}
				})
			}
			if(obj.data.parentId === value.id){
				let childData = value.datasourceContentList;
				childData[obj.data.index-1].edit = true;
				value.spread = true;
			}
		})
		if(obj.data.children){
			  $(".resourcesTitle").val(obj.data.representation);
			  $(".anotherName").val(obj.data.classAlias);
			  let keywords = obj.data.keyword||"";
			  let reg=/\\|\/|\;|\;|\，|\,|\、|\、|\^|\`|\|/g;
			  keywords = keywords.replace(reg,",");
			  let keywordList = keywords.split(',');
			  selectedKeywords = keywordList;
			  appeedKeyword();
			  $('.sourceCont').addClass('disabledNone');
			  $('.sourceTable').removeClass('disabledNone');
		}else{
			  $(".resourcesTitle").val(obj.data.columnName);
			  $(".anotherName").val(obj.data.name);
			  selectedKeywords = []
			  appeedKeyword();
			  $('.sourceTable').addClass('disabledNone');
			  $('.sourceCont').removeClass('disabledNone');
		}
		currentData = obj.data;
	}
	//删除或者增加资源树
	function operateTreeData(obj){
		if(obj.type == "del"){
			if(obj.data.datasourceContentList){
				$.ajax({
       timeout:30000,
					url: window.Http + "/data/struct/del",
					type: 'DELETE',
					headers: {
						'Authorization': "Bearer " + sessionStorage.getItem('Token')
					},
					data: {datasourceStructId:obj.data.id},
					success: function (res) {
						if(res.code == 200){
							layer.msg("删除成功", {icon: 1});
							setInfoData2();
						}else{
							layer.msg(res.msg, {icon: 2});
						}
					}
				})
			}else{
				operateData.forEach((value,index)=>{
					value.datasourceContentList.forEach((val,i)=>{
						if(val.id == obj.data.id){
							value.datasourceContentList.splice(i,1);
							half_saveFunction(value,3);
							return;
						}
					})
				})
			}

		}else if(obj.type == "add"){
			if(obj.data.datasourceContentList){
				let data = {
					columnName: "未填写",
					dataType: "5",
					name: "未填写",
					remark: "暂无",
					tableName: ""
				}
				obj.data.datasourceContentList.push(data)
				$.ajax({
       timeout:30000,
					url: window.Http + "/data/struct/save",
					type: 'POST',
					headers: {
						'Authorization': "Bearer " + sessionStorage.getItem('Token')
					},
					data: JSON.stringify(obj.data),
					contentType:"application/json",
					success: function (res) {
						if(res.code == 200){
							layer.msg("新增成功", {icon: 1});
							half_pageNum = 1;
							setInfoData2();
						}else{
							layer.msg(res.msg, {icon: 2});
						}
					}
				})
			}else{
				layer.msg("资源内容不支持下级设置");
			}

		}
	}
	//复选框选中资源树
	function checkedTreeData(obj){
		operateData.forEach((value,index)=>{
			if(obj.data === value){
				value.checked = obj.checked;
			}else if(value.datasourceContentList && value.datasourceContentList.length>0){
				let childData = value.datasourceContentList;
				childData.forEach((val,i)=>{
					if(obj.data === val){
						val.checked = obj.checked;
					}
				})
			}
		})
	}

	//处理数据显示
	function dealShowDataFun(){
		operateData.forEach((value,index)=>{
			value.title = (value.representation||"未命名") +" — " +(value.classAlias||"未命名")+" — 关键字："+value.keyword;
			value.value = value.id;
			value.edit = false;
			if(value.datasourceContentList && value.datasourceContentList.length>0){
				let childData = value.datasourceContentList;
				childData.forEach((val,i)=>{
					val.title = val.columnName+" — "+val.name;
					val.value = val.id;
					val.edit = false;
				})
				value.children = childData;
			}else{
				value.children = [];
			}

		})
		renderResources();
	}
	// //结构资源数据下一页
	// $("body").on("click",'#nextPageResources',function (e){
	// 	e.preventDefault();
	// 	half_pageNum++;
	// 	setInfoData2();
	// })
	// //结构资源数据上一页
	// $("body").on("click",'#prePageResources',function (e){
	// 	e.preventDefault();
	// 	half_pageNum--;
	// 	setInfoData2();
	// })

	//新增资源表结构
	$("body").on("click",'#addResourcesTable',function (e){
		e.preventDefault();
		let classAlias = $(".anotherName").val();
		let representation = $(".resourcesTitle").val();
		let keywords = "";
		selectedKeywords.forEach((val,index)=>{
			if(index == (selectedKeywords.length-1)){
				keywords += val;
			}else{
				keywords += (val+',');
			}
		})
		let obj = {
			id : "",
			classAlias: classAlias,
			representation: representation,
			remark: "",
			keyword:keywords,
			sourceId:infoId,
			datasourceContentList:[]
		}
		if(classAlias&&representation){
			$.ajax({
       timeout:30000,
				url: window.Http + "/data/struct/save",
				type: 'POST',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				data: JSON.stringify(obj),
				contentType:"application/json",
				success: function (res) {
					if(res.code == 200){
						layer.msg("新增成功", {icon: 1});
						half_pageNum = 1;
						setInfoData2();
					}else{
						layer.msg(res.msg, {icon: 2});
					}
				}
			})
		}else{
			layer.msg("请先填写资源表和表别名");
		}
	})
	//保存资源表结构
	$("body").on("click",'#saveResourcesTable',function (e){
		e.preventDefault();
		let classAlias = $(".anotherName").val();
		let representation = $(".resourcesTitle").val();
		let keywords = "";
		selectedKeywords.forEach((val,index)=>{
			if(index == (selectedKeywords.length-1)){
				keywords += val;
			}else{
				keywords += (val+',');
			}
		})
		let obj = {
			classAlias: classAlias,
			representation: representation,
			remark: "",
			keyword:keywords,
			sourceId:infoId
		}
		if(currentData){
			obj.id = currentData.id;
			obj.remark = currentData.remark;
			if(currentData.datasourceContentList){
				obj.datasourceContentList = currentData.datasourceContentList;
			}
		}
		if(classAlias&&representation){
			half_saveFunction(obj,1);
		}else{
			layer.msg("请先填写资源表和表别名");
		}
	})
	$("body").on("click",'#saveResourcesCont',function (e){
		e.preventDefault();
		let name = $(".anotherName").val();
		let columnName = $(".resourcesTitle").val();
		let dataType = $(".dataType").val();
		let obj = {};
		operateData.forEach((value,index)=>{
			value.datasourceContentList.forEach((val,i)=>{
				if(val.id == currentData.id){
					val.name = name;
					val.columnName = columnName;
					val.dataType = dataType;
					obj = value;
				}
			})

		})
		if(name&&columnName){
			half_saveFunction(obj,2);
		}else{
			layer.msg("请先填写资源内容");
		}
	})

	//保存表或字段
	function half_saveFunction(obj,type){
		$.ajax({
       timeout:30000,
			url: window.Http + "/data/struct/save",
			type: 'POST',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			data: JSON.stringify(obj),
			contentType:"application/json",
			success: function (res) {
				if(res.code == 200){
					if(type == 1){
						layer.msg("资源结构保存成功", {icon: 1});
					}else if(type == 2){
						layer.msg("资源内容保存成功", {icon: 1});
					}else if(type == 3){
						layer.msg("资源内容删除成功", {icon: 1});
					}
					half_pageNum = 1;
					setInfoData2();
				}else{
					layer.msg(res.msg, {icon: 2});
				}
			}
		})
	}
	// //表名/字段名
	// $('.halfArtificia').on('blur', '.resourcesTitle', function () {
	// 	let editVal = $(this).val();
	// 	operateData.forEach((value,index)=>{
	// 		if(value.edit){
	// 			value.representation = editVal;
	// 			value.title = value.representation+" — "+value.classAlias+" — 关键字："+value.keyword;
	// 		}else if(value.datasourceContentList && value.datasourceContentList.length>0){
	// 			let childData = value.datasourceContentList;
	// 			childData.forEach((val,i)=>{
	// 				if(val.edit){
	// 					val.columnName = editVal;
	// 					val.title = val.columnName+" — "+val.name;
	// 				}
	// 			})
	// 		}
	// 	})
	// 	renderResources();
	// })
	// //表别名/字段别名
	// $('.halfArtificia').on('blur', '.anotherName', function () {
	// 	let editVal = $(this).val();
	// 	operateData.forEach((value,index)=>{
	// 		if(value.edit){
	// 			value.classAlias = editVal;
	// 			value.title = value.representation+" — "+value.classAlias+" — 关键字："+value.keyword;
	// 		}else if(value.datasourceContentList && value.datasourceContentList.length>0){
	// 			let childData = value.datasourceContentList;
	// 			childData.forEach((val,i)=>{
	// 				if(val.edit){
	// 					val.name = editVal;
	// 					val.title = val.columnName+" — "+val.name;
	// 				}

	// 			})
	// 		}
	// 	})
	// 	renderResources();
	// })

	//全选资源树
	// layui.form.on('checkbox(checkedAllData)', function(data){
	// 	if(data.elem.checked){
	// 		operateData.forEach((value,index)=>{
	// 			value.checked = true;
	// 			if(value.datasourceContentList && value.datasourceContentList.length>0){
	// 				let childData = value.datasourceContentList;
	// 				childData.forEach((val,i)=>{
	// 					val.checked = true;
	// 				})
	// 			}
	// 		})
	// 	}else{
	// 		operateData.forEach((value,index)=>{
	// 			value.checked = false;
	// 			if(value.datasourceContentList && value.datasourceContentList.length>0){
	// 				let childData = value.datasourceContentList;
	// 				childData.forEach((val,i)=>{
	// 					val.checked = false;
	// 				})
	// 			}
	// 		})
	// 	}
	// 	renderResources();
	// });


	//关闭关键字弹窗
	$("body").on("click",'#showKeyWordPop',function (e){
		e.preventDefault();
		$(".keyWordPop").removeClass("disabledNone");
	})
	//关闭关键字弹窗
	$("body").on("click",'#closeKeyWordPop',function (e){
		e.preventDefault();
		$(".keyWordPop").addClass("disabledNone");
	})
	//获取弹窗左侧分类
	let keywordList = [];
	$.ajax({
       timeout:30000,
		url: window.Http + "/keyword/all/name",
		type: "GET",
		headers: {
			'Authorization': "Bearer " + sessionStorage.getItem('Token')
		},
		data:{keyword:""},
		success: function (res) {
			if (res.code === 200) {
				keywordList = res.data || [];
				if (res.data && res.data.length > 0) {
					let html = ``;
					res.data.forEach(function (val, index) {
						html += `<li data-Id="${val.id}">${val.sourceName}</li>`
					})
					$(".classifyBox").find("ul").append(html);
				}else{
					let html = `<li>暂无分类</li>`;
					$(".classifyBox").find("ul").append(html);
				}

			}
		}
	})
	//点击弹窗左侧分类li标签
	$("body .classifyBox").on("click",'li',function (e){
		e.preventDefault();
		if($(this).attr("data-Id")){
			keywordList.forEach((val, index)=> {
				if(val.id == $(this).attr("data-Id")){
					$(".keywordBox").empty();
					let html = ``;
					val.keywordList.forEach((key, i)=> {
						html += `<button type="button" class="layui-btn layui-btn-sm" style="margin-left: 10px;">${key}</button>`
					})
					$(".keywordBox").append(html);
				}
			})
		}
	})
	//关键字盒子中点击
	$("body .keywordBox").on("click",'button',function (e){
		e.preventDefault();
		if(selectedKeywords.length<3){
			let filterArray = selectedKeywords.filter((item)=>{
				return item == $(this).text();
			})
			if(filterArray.length == 0){
				selectedKeywords.push($(this).text());
				appeedKeyword();
			}
		}else{
			layer.msg("每个资源，最多支持3个关键字");
		}
	})

	//弹窗中切换是否自定义关键字
	layui.form.on('switch(customKeyword)', function(data){
		if(data.elem.checked){
			$(".chooseKeywordBox").addClass("disabledNone");
			$(".inputKeyWord").removeClass("disabledNone");
		}else{
			$(".chooseKeywordBox").removeClass("disabledNone");
			$(".inputKeyWord").addClass("disabledNone");
		}
	});
	//关键字弹窗输入自定义回车
	$(".keyWord").keydown(function(e) {
	    if (e.keyCode == 13) {
	        e.preventDefault();
			if(selectedKeywords.length<3){
				let filterArray = selectedKeywords.filter((item)=>{
					return item == $(this).val();
				})
				if(filterArray.length == 0){
					selectedKeywords.push($(this).val());
					appeedKeyword();
				}
			}else{
				layer.msg("每个资源，最多支持3个关键字");
			}
	    }
	});
	//删除已有标签
	$("body .keyWordLable").on("click",'.layui-icon',function (e){
		e.preventDefault();
		if(!$(this).parent().attr('id')){
			let currentvalue = $(this).parent().text();
			let filterArray = selectedKeywords.filter((item)=>{
				return item != currentvalue;
			})
			selectedKeywords = filterArray;
			appeedKeyword();
		}

	})
	//向页面上添加关键字并处理逻辑
	let selectedKeywords = [];
	function appeedKeyword(){
		if(selectedKeywords.length < 3){
			let html= "";
			selectedKeywords.forEach((key, i)=> {
				html += `<button type="button" class="layui-btn layui-btn-primary">${key}<i class="layui-icon layui-icon-reduce-circle" style="margin-left:5px"></i></button>`
			})
			html += `<button type="button" class="layui-btn layui-btn-primary" id="showKeyWordPop">添加关键字 <i class="layui-icon layui-icon-add-circle"></i></button>`
			$(".keyWordLable").empty().append(html);
		}else if(selectedKeywords.length == 3){
			let html= "";
			selectedKeywords.forEach((key, i)=> {
				html += `<button type="button" class="layui-btn layui-btn-primary">${key}<i class="layui-icon layui-icon-reduce-circle" style="margin-left:5px"></i></button>`
			})
			$(".keyWordLable").empty().append(html);
		}else{
			layer.msg("每个资源，最多支持3个关键字");
		}
	}


	/***********导入资源文件程序处理结束***************/





	/***********自动获取资源程序处理***************/
	//执行规则文件
	$("body").on("click",'#executionFile',function (e){
		e.preventDefault();
		uploadFile2(ruleFile);
	})
	function uploadFile2(ruleFile) {
		loadIndex = layer.load(1); //换了种风格
	    var form = new FormData();
		if(ruleFile){
			form.append('rule', ruleFile);
		}
		form.append('sourceId', infoId);
	    $.ajax({
       timeout:30000,
			url:window.Http+"/datasourceBase/automatic",
			type:'POST',
			headers: {
			　　'Authorization':"Bearer "+sessionStorage.getItem('Token')
			},
			data:form,
			mimeType:"multipart/form-data",
			contentType:false,
			processData:false,
			dataType:"json",
			success:function (res){
				layer.close(loadIndex);
				if(res.code == 200){
					queryDataStatus();//立即执行一次
					if(!analysis_timer){
						analysis_timer = setInterval(function(){
						   queryDataStatus();
						},5000)
					}
				}else{
					layer.msg(res.msg);
				}
			},
			error:function(err){
				layer.close(loadIndex);
				layer.msg(err.msg);
			}
	    })
	};

	/***********自动获取资源程序处理结束***************/


})
